package com.ray.stp;

import cn.dev33.satoken.stp.StpInterface;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.ray.model.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StpInterfaceImpl implements StpInterface {

    @Value("${spring.datasource.base.name}")
    private String base;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> permissions = new ArrayList<String>();
        User user = User.dao.findById(loginId);
        if(user.getBoolean("is_coder")) {
            permissions =  Db.use(base).query("select no from permissions");
        }else {
            permissions = Db.use(base).query("SELECT t1.no FROM permissions t1"
                    + " LEFT JOIN role_permission t2 ON t1.no = t2.permission_no"
                    + " LEFT JOIN user_role t3 ON t2.role_no = t3.role_no"
                    + " WHERE t3.userid = ?",user.getUserid());
        }
        return permissions;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roles = new ArrayList<String>();
        User user = User.dao.findById(loginId);
        if(user.getBoolean("is_coder")) {
            roles.add("coder");
        }else {
            roles = Db.use(base).query("SELECT role_no"
                    + " FROM user_role WHERE userid = ? AND region = ?",user.getUserid(),user.getRegion());
        }
        return roles;
    }
}
